package providers

import (
	"context"
	"fmt"
	"xagent/internal/streaming"
)

// KimiProvider implements LLMProvider using Kimi's API
type KimiProvider struct {
	config *ProviderConfig
}

// NewKimiProvider creates a new Kimi provider
func NewKimiProvider(config *ProviderConfig) (*KimiProvider, error) {
	if config.APIKey == "" {
		return nil, fmt.Errorf("Kimi API key is required")
	}

	return &KimiProvider{
		config: config,
	}, nil
}

// Complete implements LLMProvider
func (p *KimiProvider) Complete(ctx context.Context, prompt string, options *CompletionOptions) (string, error) {
	return p.Chat(ctx, []Message{{Role: "user", Content: prompt}}, &ChatOptions{
		Model:       options.Model,
		MaxTokens:   options.MaxTokens,
		Temperature: options.Temperature,
		TopP:        options.TopP,
		Stop:        options.Stop,
	})
}

// Chat implements LLMProvider
func (p *KimiProvider) Chat(ctx context.Context, messages []Message, options *ChatOptions) (string, error) {
	// TODO: Implement Kimi chat API
	return "", fmt.Errorf("not implemented")
}

// StreamChat implements LLMProvider
func (p *KimiProvider) StreamChat(ctx context.Context, messages []Message, options *ChatOptions) (<-chan streaming.StreamEvent, error) {
	ch := make(chan streaming.StreamEvent)

	go func() {
		defer close(ch)

		handler := &streaming.DefaultStreamHandler{}
		if err := p.StreamChatWithHandler(ctx, messages, options, handler); err != nil {
			ch <- streaming.StreamEvent{
				Error: err,
				Done:  true,
			}
			return
		}

		text := handler.GetText()
		ch <- streaming.StreamEvent{
			Token: text,
			Done:  true,
		}
	}()

	return ch, nil
}

// StreamChatWithHandler implements LLMProvider
func (p *KimiProvider) StreamChatWithHandler(ctx context.Context, messages []Message, options *ChatOptions, handler streaming.StreamHandler) error {
	// TODO: Implement Kimi streaming chat API
	return fmt.Errorf("not implemented")
}

// GetConfig returns the provider configuration
func (p *KimiProvider) GetConfig() *ProviderConfig {
	return p.config
}
